package com.liwalo.interceptors;

import java.io.Serializable;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.StrutsStatics;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
import com.opensymphony.xwork2.util.TextParseUtil;

public class AuthenticationInterceptor extends AbstractInterceptor implements
		Serializable {
	private static final long serialVersionUID = -1784784153643651554L;

	public static final String authenticationSessionField = new String(
			"authenticated");
	private static final String authenticationRequiredResult = "authentication_required";
	
	public static final String DEFAULT_ACTION = "%defaultAction%";
	
	
	@SuppressWarnings("unchecked")
	private Set<String> excludeActions = Collections.EMPTY_SET;

	@Override
	public String intercept(ActionInvocation invocation) throws Exception {
		Map<String, Object> session = invocation.getInvocationContext().getSession();
		String actionName = invocation.getProxy().getActionName();
		
		if (actionName != null && "".equalsIgnoreCase(actionName.trim())){	
			actionName = DEFAULT_ACTION;
		}

		Object authenticationObject = session.get(authenticationSessionField);

		if (excludeActions.contains(actionName)
				|| (authenticationObject != null
						&& authenticationObject instanceof Boolean && authenticationObject
							.equals(Boolean.TRUE))) {
			return invocation.invoke();
		}

		if (!excludeActions.contains(actionName)) {
			final ActionContext context = invocation.getInvocationContext ();
		    HttpServletRequest request = (HttpServletRequest) context.get(StrutsStatics.HTTP_REQUEST);
		    String queryString = request.getQueryString();
		    String requestURI = request.getRequestURI().substring(request.getContextPath().length());
			session.put("savedUrl", requestURI+(queryString==null?"":("?"+queryString)));
		}

		return authenticationRequiredResult;

	}

	public void setExcludeActions(String values) {
		if (values != null) {
			this.excludeActions = TextParseUtil
					.commaDelimitedStringToSet(values);
		}
	}

}